/*
* jinlanbao
*/
package com.jlb.zx.ctrl;

import com.baidu.fsg.uid.UidGenerator;
import com.jlb.active.service.ActivePoolSV;
import com.jlb.core.enums.YNEnum;
import com.jlb.core.tools.DateTools;
import com.jlb.core.tools.FileUtil;
import com.jlb.core.tools.StringTools;
import com.jlb.core.tools.redis.RedisUtils;
import com.jlb.core.tools.security.Md5;
import com.jlb.miner.entity.MinerItem;
import com.jlb.miner.service.MinerItemSV;
import com.jlb.setting.dao.SettingDAO;
import com.jlb.setting.entity.Setting;
import com.jlb.star.service.StarLevelSV;
import com.jlb.user.entity.*;
import com.jlb.user.service.*;
import com.jlb.zx.entity.ZxKuangFen;
import com.jlb.zx.entity.ZxMember;
import com.jlb.zx.service.ZxKuangFenSV;
import com.jlb.zx.service.ZxMemberSV;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 控制器
 *
 * @author jinlanbao
 */
@RestController
@RequestMapping("/zxMember")
@Slf4j
@Api(value = "控制器", description = "控制器")
public class ZxMemberCtrl {

    @Resource
    protected RedisUtils redisUtils;

    @Resource
    private ZxMemberSV zxMemberSV;

    @Resource
    private UserSV userSV;

    @Resource
    private StarLevelSV starLevelSV;

    @Resource
    private ActivePoolSV activePoolSV;

    @Resource
    private MinerItemSV minerItemSV;


    @Resource
    private UserOreSV userOreSV;

    @Resource
    private UserMinerSV userMinerSV;

    @Resource
    private SettingDAO settingDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Resource
    private ZxKuangFenSV zxKuangFenSV;

    @Resource
    private UserJlbSV userJlbSV;

    @Resource
    private UserActiveSV userActiveSV;


    /**
     * 生成sql文件
     *
     * @return 总条数
     */
    @ApiOperation(value = " 生成sql文件", notes = " 生成sql文件")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createsql")
    @ResponseBody
    public void createsql() {
        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        StringBuffer zxmemberFlag;
        StringBuffer zxmember = new StringBuffer();
        String createTime;
        for (ZxMember member : zxMembers) {
            //生成支付方式sql保存到文件中
            zxmemberFlag = new StringBuffer();
            zxmemberFlag.append("INSERT INTO user(code,account,password,real_name,pin_password,state,phone,star,leader,id_card,alipay,wechat,nick_name,createTime,updateTime) VALUES('");
            zxmemberFlag.append(uidGenerator.getUID()).append("','");
            zxmemberFlag.append(member.getUsernumber()).append("','");
            zxmemberFlag.append(Md5.md5(member.getUsernumber())).append("','");
            zxmemberFlag.append(member.getRealname()).append("','");
            zxmemberFlag.append(Md5.md5(member.getUsernumber())).append("','");
            if ("-1".equals(member.getStatus())) {
                zxmemberFlag.append(UserState.Frozen.name()).append("','");
            } else {
                zxmemberFlag.append(UserState.Active.name()).append("','");
            }
            if (StringTools.isEmpty(member.getMobile())) {
                zxmemberFlag.append("','");
            } else {
                zxmemberFlag.append(member.getMobile()).append("','");
            }
            zxmemberFlag.append(member.getUserrank()).append("','");
            zxmemberFlag.append(YNEnum.N.name()).append("','");
            if (StringTools.isEmpty(member.getIdcard())) {
                zxmemberFlag.append("','");
            } else {
                zxmemberFlag.append(member.getIdcard()).append("','");
            }
            if (StringTools.isEmpty(member.getAlipay())) {
                zxmemberFlag.append("','");
            } else {
                zxmemberFlag.append(member.getAlipay()).append("','");
            }
            if (StringTools.isEmpty(member.getWechat())) {
                zxmemberFlag.append("','");
            } else {
                zxmemberFlag.append(member.getWechat()).append("','");
            }
            if (StringTools.isEmpty(member.getNickname())) {
                zxmemberFlag.append("','");
            } else {
                zxmemberFlag.append(member.getNickname()).append("','");
            }
            createTime = DateTools.secondToDate(Long.valueOf(member.getRegTime()), "yyyy-MM-dd HH:mm:ss");
            zxmemberFlag.append(createTime).append("','");
            zxmemberFlag.append(createTime).append("'");
            zxmemberFlag.append(");").append("\r\n");
            zxmember.append(zxmemberFlag);
        }
        try {
            File file = FileUtil.creatFile("C:\\user", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] paymentSqlByte = zxmember.toString().getBytes();
            fos.write(paymentSqlByte);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成用户银行卡sql
     */
    @ApiOperation(value = " 生成用户银行卡sql", notes = " 生成用户银行卡sql")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createBanksql")
    @ResponseBody
    public void createBanksql() {
        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        StringBuffer zxmember = new StringBuffer();
        User user;
        StringBuffer bankSbFlag;
        StringBuffer bankSb = new StringBuffer();
        for (ZxMember member : zxMembers) {
            if (!StringTools.isEmpty(member.getBanknumber())) {
                user = userSV.loadByAccountForCreateSql(member.getUsernumber());
                bankSbFlag = new StringBuffer();
                bankSbFlag.append("INSERT INTO user_bank_card(user_code,bank_name,bank_number,bank_man,sub_bank) VALUES('");
                bankSbFlag.append(user.getCode()).append("','");
                bankSbFlag.append(member.getBankname()).append("','");
                bankSbFlag.append(member.getBanknumber()).append("','");
                bankSbFlag.append(member.getBankholder()).append("','");
                bankSbFlag.append(member.getBranchname()).append("'");
                bankSbFlag.append(");").append("\r\n");
                bankSb.append(bankSbFlag);
            }
        }
        try {
            File file = FileUtil.creatFile("C:\\userBank", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] paymentSqlByte = bankSb.toString().getBytes();
            fos.write(paymentSqlByte);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 生成推荐关系sql文件
     *
     * @return 总条数
     */
    @ApiOperation(value = " 生成推荐关系sql文件", notes = " 生成推荐关系sql文件")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createGroupsql")
    @ResponseBody
    public void createGroupsql() {
        long beginTime = System.currentTimeMillis();
        int layers = Integer.parseInt(settingDAO.loadByK(Setting.Key.Layers.name()).getV());
        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        StringBuffer zxmember = new StringBuffer();
        User user;
        User fatherUser;
        ZxMember fatherMember;
        String groups;
        String[] groupsArr;
        StringBuffer userGroupFlagSb;
        StringBuffer userGroupSb = new StringBuffer();
        StringBuffer myGroupFlagSb;
        StringBuffer myGroupSb = new StringBuffer();
        for (ZxMember member : zxMembers) {
            userGroupFlagSb = new StringBuffer();
            groups = member.getTuijianids().toString();
            if (groups.length() > 1) {
                groups = groups.substring(1, groups.length() - 1);
                groupsArr = groups.split(",");
                if (groupsArr.length > 0) {
                    //在user表查询会员信息
                    user = userSV.loadByAccountForCreateSql(member.getUsernumber());
                    //在member表中查询出推荐人会员信息
                    fatherMember = zxMemberSV.loadByUid(groupsArr[groupsArr.length - 1]);
                    fatherUser = userSV.loadByAccountForCreateSql(fatherMember.getUsernumber());
                    userGroupFlagSb.append("INSERT INTO user_group(user_code,pre_user_code,createTime) VALUES('");
                    userGroupFlagSb.append(user.getCode()).append("','");
                    userGroupFlagSb.append(fatherUser.getCode()).append("','");
                    String createTime = DateTools.secondToDate(Long.valueOf(member.getRegTime()), "yyyy-MM-dd HH:mm:ss");
                    userGroupFlagSb.append(createTime).append("'");
                    userGroupFlagSb.append(");").append("\r\n");
                    userGroupSb.append(userGroupFlagSb);

                    //生成自上而下的关系
                    if (groupsArr.length > layers) {
                        groupsArr = Arrays.copyOfRange(groupsArr, groupsArr.length - layers, groupsArr.length);
                    }
                    int total = 0;
                    for (int i = groupsArr.length - 1; i >= 0; i--) {
                        fatherMember = zxMemberSV.loadByUid(groupsArr[i]);
                        fatherUser = userSV.loadByAccountForCreateSql(fatherMember.getUsernumber());
                        total = total + 1;
                        myGroupFlagSb = new StringBuffer();
                        myGroupFlagSb.append("INSERT INTO my_group(user_code,sub_user_code,sub_level) VALUES('");
                        myGroupFlagSb.append(fatherUser.getCode()).append("','");
                        myGroupFlagSb.append(user.getCode()).append("','");
                        myGroupFlagSb.append(total).append("'");
                        myGroupFlagSb.append(");").append("\r\n");
                        myGroupSb.append(myGroupFlagSb);
                    }
                }
            }
        }
        try {
            File file = FileUtil.creatFile("C:\\userGroup", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] paymentSqlByte = userGroupSb.toString().getBytes();
            fos.write(paymentSqlByte);
            fos.flush();
            fos.close();

            File myGroup = FileUtil.creatFile("C:\\myGroup", "sql");
            FileOutputStream myfos = new FileOutputStream(myGroup);
            byte[] mypaymentSqlByte = myGroupSb.toString().getBytes();
            myfos.write(mypaymentSqlByte);
            myfos.flush();
            myfos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("用时>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + (endTime - beginTime) / 1000 + "秒");
    }

    /***
     * 生成用户激活币
     * @param
     */
    @ApiOperation(value = " 生成用户激活币", notes = " 生成用户激活币")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createActiveSql")
    @ResponseBody
    public void createActiveSql() {

        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        Map<String, Object> params;

        Double active;
        User user;
        int count;
        StringBuffer userActiveSb = new StringBuffer();
        StringBuffer userActiveSbFlag;
        for (ZxMember member : zxMembers) {
            user = userSV.loadByAccountForCreateSql(member.getUsernumber());
            params = new HashedMap();
            params.put("userCode", user.getCode());
            active = member.getHasmoney5();
            //分配给用户
            userActiveSbFlag = new StringBuffer();
            userActiveSbFlag.append("INSERT INTO user_active(user_code,active) VALUES('");
            userActiveSbFlag.append(user.getCode()).append("','");
            userActiveSbFlag.append(active.intValue()).append("'");
            userActiveSbFlag.append(");").append("\r\n");
            userActiveSb.append(userActiveSbFlag);
        }
        try {
            File file = FileUtil.creatFile("C:\\actives", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] supplierSqlByte = userActiveSb.toString().getBytes();
            fos.write(supplierSqlByte);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成用户矿机
     * @param args
     */

    /**
     生成用户金兰宝
     */

    /**
     * 生成用户押金
     */
    @ApiOperation(value = " 生成用户押金sql", notes = " 生成用户押金sql")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createUserDepositSql")
    @ResponseBody
    public void createUserDepositSql() {
        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        Double deposit;
        StringBuffer userDepositSbFlag;
        StringBuffer userDepositSb = new StringBuffer();
        User user;
        for (ZxMember member : zxMembers) {
            deposit = member.getYajin();
            if (deposit.intValue() > 0) {
                user = userSV.loadByAccountForCreateSql(member.getUsernumber());
                userDepositSbFlag = new StringBuffer();
                userDepositSbFlag.append("INSERT INTO user_deposit(user_code,deposit,star_level,state,returnTime) VALUES('");
                userDepositSbFlag.append(user.getCode()).append("','");
                userDepositSbFlag.append(deposit.intValue()).append("','");
                userDepositSbFlag.append(user.getStar()).append("','");
                userDepositSbFlag.append(UserDepositState.Frozen.name()).append("','");
                Date date = DateTools.calculateByYear(user.getCreateTime(), 1);
                String returnTime = DateTools.date2String("yyyy-MM-dd HH:mm:ss", date);
                userDepositSbFlag.append(returnTime).append("'");
                userDepositSbFlag.append(");").append("\r\n");
                userDepositSb.append(userDepositSbFlag);
            }
        }
        try {
            File file = FileUtil.creatFile("C:\\userDeposit", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] paymentSqlByte = userDepositSb.toString().getBytes();
            fos.write(paymentSqlByte);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 生成用户矿石sql
     */
    @ApiOperation(value = " 生成用户矿石sql", notes = " 生成用户矿石sql")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createUserOreSql")
    @ResponseBody
    public void createUserOreSql() {
        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        Double userOre;
        StringBuffer userOreSbFlag;
        StringBuffer userOreSb = new StringBuffer();
        User user;
        int result;
        int totalore;
        for (ZxMember member : zxMembers) {
            userOre = member.getHasmoney3();
            user = userSV.loadByAccountForCreateSql(member.getUsernumber());
            userOreSbFlag = new StringBuffer();
            userOreSbFlag.append("INSERT INTO user_ore(user_code,ore,layer_total_ore,state,refine_total_ore) VALUES('");
            userOreSbFlag.append(user.getCode()).append("','");
            userOreSbFlag.append(0).append("','");

            result = userOreSV.calculateUnclaimedOre(user.getCode());
            totalore = result - member.getDmoney().intValue();
            if (totalore < 0) {
                totalore = 0;
            }
            if (member.getUserrank().intValue() == 0) {
                totalore = 0;
            }
            userOreSbFlag.append(totalore).append("','");
            userOreSbFlag.append(UserOreState.Active.name()).append("','");
                /*if (UserState.Active.name().equals(user.getState())) {
                    userOreSbFlag.append(UserOreState.Active.name()).append("','");
                } else {
                    userOreSbFlag.append(UserOreState.Stop.name()).append("','");
                }*/
            userOreSbFlag.append(userOre.intValue()).append("'");
            userOreSbFlag.append(");").append("\r\n");
            userOreSb.append(userOreSbFlag);
        }
        try {
            File file = FileUtil.creatFile("C:\\userOre", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] paymentSqlByte = userOreSb.toString().getBytes();
            fos.write(paymentSqlByte);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 生成用户矿石sql
     */
   /* @ApiOperation(value = " 生成用户矿石sql", notes = " 生成用户矿石sql")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createUserOreSql")
    @ResponseBody
    public void createUserOreSql() {
        List<ZxMember> zxMembers = zxMemberSV.listForCreateSql();
        Double userOre;
        User user;
        UserOre userOreFlag;
        ZxMember zxMemberFlag;
        Map<String, Object> params;
        for (ZxMember member : zxMembers) {
            userOre = member.getHasmoney3();
            user = userSV.loadByAccountForCreateSql(member.getUsernumber());
            if (user != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("userCode", user.getCode());
                userOreFlag = userOreSV.load(map);
                if (userOreFlag == null) {
                    userOreFlag = new UserOre();
                    userOreFlag.setUserCode(user.getCode());
                    userOreFlag.setOre(0);
                    userOreFlag.setRefineTotalOre(userOre.intValue());
                    params = new HashedMap();
                    params.put("account", member.getUsernumber());
                    zxMemberFlag = zxMemberSV.loadBonus(params);
                    userOreFlag.setLayerTotalOre(zxMemberFlag == null ? 0 : zxMemberFlag.getYajin().intValue());
                    if (UserState.Active.name().equals(user.getState())) {
                        userOreFlag.setState(UserOreState.Active.name());
                    } else {
                        userOreFlag.setState(UserOreState.Stop.name());
                    }
                    userOreFlag.setRefineTotalOre(0);
                    userOreSV.save(userOreFlag);
                }
            }
        }
    }*/

    /***
     * 校正金兰宝，矿石账户
     */
    @ApiOperation(value = " 校正金兰宝，矿石账户", notes = " 校正金兰宝，矿石账户")
    @ApiImplicitParams({
    })
    @GetMapping(value = "checkJLBOreAccount")
    @ResponseBody
    public void checkJLBOreAccount() {
        List<User> userList = userSV.list(new FastHashMap());
        Integer limitDay = Integer.valueOf(settingDAO.loadByK(Setting.Key.User_Jlb_Limit_Day.name()).getV());
        userList.forEach(user -> {
            Map<String, Object> param = new HashMap<>();
            param.put("userCode", user.getCode());
            UserMiner userMiner = userMinerSV.loadByUserCode(user.getCode());
            if (userMiner != null) {
                UserJlb userJlb = userJlbSV.load(param);
                if (userJlb == null) {
                    log.debug("jlb:" + user.getAccount());
                    param.clear();
                    param.put("code", userMiner.getMinerCode());
                    MinerItem minerItem = minerItemSV.load(param);
                    userJlb = new UserJlb();
                    userJlb.setUserCode(user.getCode());
                    userJlb.setState(UserJlbState.Active.name());
                    userJlb.setJlb(0);
                    userJlb.setRelease(0);
                    userJlb.setDigInTotalJlb(0);
                    userJlb.setDigInJlb(minerItem.getDailyIncome());
                    userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
                    userJlbSV.save(userJlb);
                }

                if (user.getStar() > 0) {
                    UserOre userOre = userOreSV.loadByUserCode(user.getCode());
                    if (userOre == null) {
                        log.debug("ore:" + user.getAccount());
                        userOreSV.save(new UserOre().init(user.getCode()));
                    }
                }
            }
        });
    }

    /***
     * 生成用户jlb sql
     */
    @ApiOperation(value = "生成用户jlb sql", notes = "生成用户jlb sql")
    @ApiImplicitParams({
    })
    @GetMapping(value = "createUserJlb")
    @ResponseBody
    public void createUserJlb() {
        List<ZxMember> zxMembers = zxMemberSV.list(new HashMap());
        final double[] a = {0};
        final double[] b = {0};
        List<String> stringList = new ArrayList<>();
        zxMembers.forEach(zxMember -> {
            if (zxMember != null) {
                Map<String, Object> param = new HashMap<>();
                param.put("account", zxMember.getUsernumber());
                User user = userSV.load(param);
                if (user != null) {
                    param.clear();
                    param.put("userCode", user.getCode());
                    UserJlb userJlb = userJlbSV.load(param);
                    if (userJlb == null) {
                        param.clear();
                        param.put("kj2", user.getAccount());
                        ZxKuangFen zxKuangFen = zxKuangFenSV.load(param);
                        userJlb = new UserJlb();
                        userJlb.setUserCode(user.getCode());
                        userJlb.setCode(String.valueOf(uidGenerator.getUID()));
                        userJlb.setState(UserJlbState.Active.name());
                        int jlb = (int) (zxMember.getHasmoney1() + zxMember.getHasmoney2() + zxMember.getHasmoney4());
                        userJlb.setJlb(jlb);
                        if (zxKuangFen != null) {
                            userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
                            userJlb.setDigInJlb(String.valueOf(zxKuangFen.getKj9().intValue()));
                            userJlb.setDigInTotalJlb(zxKuangFen.getKj7().intValue());
                        } else {
                            userJlb.setDigInJlbState(UserJlbMinerState.Init.name());
                            userJlb.setDigInJlb("0");
                            userJlb.setDigInTotalJlb(0);
                        }
                        userJlb.setMallTotalJlb(0);
                        userJlb.setRelease(0);
                        userJlbSV.save(userJlb);//jlb 数据

                        //矿机数据
                        if (zxKuangFen != null) {
                            UserMiner userMinerLoad = userMinerSV.loadByUserCode(user.getCode());
                            if (userMinerLoad == null) {
                                double multiple = 1.5;
                                int upper_limit = (int) ((multiple * zxKuangFen.getKj3().intValue()));
                                UserMiner userMiner = new UserMiner();
                                userMiner.setUserCode(user.getCode());
                                if (zxKuangFen.getKj3().intValue() == 200) {
                                    userMiner.setMinerCode("1139232859722702848");
                                } else if (zxKuangFen.getKj3().intValue() == 500) {
                                    userMiner.setMinerCode("1139234148212891648");
                                } else if (zxKuangFen.getKj3().intValue() == 1100) {
                                    userMiner.setMinerCode("1139234680788836352");
                                }
                                userMiner.setDailyIncome(String.valueOf(zxKuangFen.getKj9().intValue()));
                                userMiner.setState(UserMinerState.Working.name());
                                userMiner.setPower(String.valueOf(zxKuangFen.getKj3()));
                                userMiner.setUpperLimit(String.valueOf(upper_limit));
                                userMiner.setMultiple(String.valueOf(multiple));
                                userMiner.setCreateTime(new Date());
                                userMiner.setUpdateTime(new Date());
                                userMinerSV.save(userMiner);
                            }
                        }
                    }


                }


            }
        });

    }


}
